import React, { useCallback, useEffect, useRef, useState } from "react";
import "./tabs.css";

function Tabs(props) {

  // 视图大小变化时,让位置归0
  window.addEventListener('resize', () => {
    setTabsbigLeft(0)
  })

  // 控制左右滑动 
  const [TabsbigLeft, setTabsbigLeft] = useState(0)

  // 获取主盒子元素
  const tabsRef = useRef()
  const tabsbigRef = useRef()

  // 设置左右按钮的显示隐藏 
  const [ArrowLeftShow, setArrowLeftShow] = useState('none')
  const [ArrowRightShow, setArrowRightShow] = useState('block')

  // 监听 TabsbigLeft 变化
  useEffect(() => {
    if (!TabsbigLeft <= 0) {
      // 获取元素宽度 
      let Tabswidth = parseInt(window.getComputedStyle(tabsRef.current).width)
      let TabsbigWidth = parseInt(window.getComputedStyle(tabsbigRef.current).width)
      // 判断大小设置左右按钮的显示隐藏
      if (TabsbigLeft + Tabswidth >= TabsbigWidth) {
        setArrowRightShow('none')
        setArrowLeftShow('block')
      }
      else {
        setArrowRightShow('block')
        setArrowLeftShow('block')
      }
    } else if (TabsbigLeft <= 0) {
      setArrowRightShow('block')
      setArrowLeftShow('none')
    }
  }, [TabsbigLeft])

  // 左右按钮的点击事件
  const ArrowRight = (state) => {

    // 获取元素宽度 
    let Tabswidth = parseInt(window.getComputedStyle(tabsRef.current).width)
    let TabsbigWidth = parseInt(window.getComputedStyle(tabsbigRef.current).width)

    // 根据点击的左右按钮设置 "绝对定位" "TabsbigLeft" 定位距离
    if (state === 'right') {
      if (TabsbigLeft + Tabswidth * 2 - 200 > TabsbigWidth) {
        setTabsbigLeft(TabsbigLeft + (TabsbigWidth - (TabsbigLeft + Tabswidth)))
      } else if (TabsbigLeft + Tabswidth * 2 - 200 <= TabsbigWidth) {
        setTabsbigLeft(TabsbigLeft + Tabswidth - 200)
      }
    } else {
      if (TabsbigLeft < Tabswidth) {
        setTabsbigLeft(0)
      } else {
        setTabsbigLeft(TabsbigLeft - Tabswidth + 200)
      }
    }
  }

  return (
    <div className="tabs" ref={tabsRef}>
      {/* 左右箭头 */}
      <div className="tabs-arrow arrow-left" style={{ display: `${ArrowLeftShow}` }} onClick={() => ArrowRight('left')} ></div>
      <div className="tabs-arrow arrow-right" style={{ display: `${ArrowRightShow}` }} onClick={() => ArrowRight('right')}></div>

      {/* 装内容的盒子 */}
      <div className="tabs-item" >
        <div className="tabsbig" ref={tabsbigRef} style={{ width: `${props.DataListLength * props.DomWidth}px`, left: `-${TabsbigLeft}px` }}>
          {
            React.Children.map(props.children, (child, index) => {
              return child;
            })
          }
        </div>
      </div>
    </div>
  );
}

export default Tabs;
